package cn.yuanqiao.archive.storeRoom.service.impl;

import cn.yuanqiao.archive.storeRoom.domain.Grid;
import cn.yuanqiao.archive.storeRoom.domain.Shelf;
import cn.yuanqiao.archive.storeRoom.domain.Storeroom;
import cn.yuanqiao.archive.storeRoom.mapper.BoxMapper;
import cn.yuanqiao.archive.storeRoom.mapper.GridMapper;
import cn.yuanqiao.archive.storeRoom.mapper.ShelfMapper;
import cn.yuanqiao.archive.storeRoom.mapper.StoreroomMapper;
import cn.yuanqiao.archive.storeRoom.service.IWarehousePreviewService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

;

@Service
public class WarehousePreviewServiceImpl implements IWarehousePreviewService {


    @Autowired
    private ShelfMapper shelfMapper;
    @Autowired
    private GridMapper gridMapper;

    @Autowired
    private BoxMapper boxMapper;

    @Autowired
    private StoreroomMapper storeroomMapper;
    @Override
    public Map<String, String> createStorageCubageHTML(String shelfId) {
        String code= SecurityUtils.getTenantCode().toUpperCase();
        if(StringUtils.isEmpty(code)){
            throw new ServiceException("TenantCode is null");
        }
        String imageBasePath = "../../../../../img/";
        float tableWidth = 550;
        float tableHeight = 230;
        float tdLineWidth = 1;

        String trStyle = "";
        String tdStyle = "border-width:1px;cursor:pointer;";
        String tdClickEvent = "showInfo(grid,guiid,storeid,'position')";

       // shelfId = shelfId.substring(2, shelfId.length());
        //A,B面
        Grid grid=new Grid();
        grid.setShelfId(Long.parseLong(shelfId));
        grid.setGridSide("A");
        List<Grid> geList =gridMapper.selectGridList(grid,SecurityUtils.getTenantCode().toUpperCase());//result   A面的所有格子
        Shelf shelf = shelfMapper.getShelfById(Long.parseLong(shelfId),code);//result1   当前的档案柜
        //int iCol = danganGuiList.get(0).get("SHELF_STAND")==""?0:Integer.parseInt(danganGuiList.get(0).get("SHELF_STAND"));//竖格的数量
       // int iRow = danganGuiList.get(0).get("SHELF_CROSS")==""?0:Integer.parseInt(danganGuiList.get(0).get("SHELF_CROSS"));//横格的数量
        int iCol =shelf.getShelfStand();
        int iRow =shelf.getShelfCross();
        float imageWidth = (tableWidth - (iCol - 1) * tdLineWidth) / iCol;//格子背景图片的宽
        float imageHeight = (tableHeight - (iRow - 1) * tdLineWidth) / iRow;//格子背景图片的高
        float imageTdWidth = 1;
        if (null != geList && geList.size() > 0) {
            imageTdWidth = imageWidth /  30;//计算格子中的盒子图片的宽度
            imageTdWidth = imageTdWidth < 1 ? 1 : imageTdWidth;
        }

        String html = new String();
        StringBuffer sb = new StringBuffer(500);

        for(int r=0;r<iRow;r++) {//横    6
            int pai=r+1;
            sb.append("<tr ").append("style='").append(trStyle).append("'>");
            for (int c = 0; c < iCol; c++) {//竖格的数量   1 2    列   5
                int lie=c+1;
                if (null == geList || geList.size() == 0) {
                    break;
                }
                int orderNo = pai+(lie-1)*iRow;
                Grid grid1=geList.get(orderNo - 1);
                String positionString=shelf.getStoreCde()+" "+shelf.getKfqy()+" "+shelf.getShelfCode()+" "+"A面"+" "+grid1.getGridCode();
                String tdClickEventTmp = tdClickEvent.replaceAll("grid", grid1.getGridId().toString());
                tdClickEventTmp = tdClickEventTmp.replaceAll("guiid", grid1.getShelfId().toString());
                tdClickEventTmp = tdClickEventTmp.replaceAll("storeid", shelf.getStoreId().toString());
                tdClickEventTmp = tdClickEventTmp.replaceAll("position", positionString);

                StringBuffer title = new StringBuffer();
                title.append("存址编号：");
                title.append(grid1.getGridName());
                StringBuffer sbImageTd = new StringBuffer();

                Long grid_id = grid1.getGridId();
                int count = boxMapper.getUpShelvesNum(grid_id,code);

                if (count <= 0) {
                    for (int j = 0; j <  30; j++) {
                        sbImageTd.append("<td class='EmptyRack' style='width:" + imageTdWidth + "px;height:"
                                + imageHeight + "px;'></td>");
                    }
                } else {
                    int index = 0;
                    int k = 0;
                    for (int i = 0; i <  30; i++) {
                        if (index ==  30) {
                            break;
                        }
                        index++;
                        if (k < count) {
//                            sbImageTd.append("<td><img class=\"img\" src='" + imageBasePath + "cubage_use_1.jpg' width='"
//                                    + imageTdWidth + "' height='" + imageHeight + "' style=\" background-color: #d69632;\" /></td>");
                            sbImageTd.append("<td class='listClass' style='width:" + imageTdWidth + "px;height:" + imageHeight +
                                    "px;'></td>");
                            k++;

                        } else {
                            sbImageTd.append("<td class='EmptyRack' style='width:" + imageTdWidth + "px;height:"
                                    + imageHeight + "px;'></td>");
                        }
                    }
                 /*   float image0s = Float.parseFloat(grid1.getGridWidth().toString()) / 30 - Float.parseFloat(boxMapper.getUpShelvesNumByFolderId(grid1.getGridId(),code)+"");
                    image0s = image0s < 0 ? 0 : image0s;
                    for (int j = 0; j < image0s; j++) {
                        if (index == Float.parseFloat(grid1.getGridWidth().toString()) / 30) {
                            break;
                        }
                        index++;
                        sbImageTd.append("<td class='EmptyRack' style='width:" + imageTdWidth + "px;height:"
                                + imageHeight + "px;'></td>");

                    }*/
                }

                //String tdText = danganGeMap.get("GRID_STDNUM") + "-" + danganGeMap.get("GRID_CRSNUM");//
                int tdText =pai+(lie-1)*iRow;
                sb.append("<td id=\"" + grid1.getGridId() + "\"").append("style='").append(tdStyle)
                        .append("background-image: linear-gradient( #c9caca, #737373);height:"+imageHeight+"px;")//整个格子的背景颜色
                        .append("' align='center' @click=\"" + tdClickEventTmp + "\"")
                        .append("title=\"" + title.toString() + "\">").append("<div>");
                sb.append(
                        "<table style=\"position:relative;z-index:1;top:0px;left:0px;\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
                sb.append(sbImageTd);//所有的盒
                sb.append("</tr></table>");
                sb.append("<div style='position:relative;z-index:2;top:-15px;left:0px;height:0px;'>");
                sb.append("<font color='#ffffff' style='font-size:10px'>" +tdText+"格");
                sb.append("</font></div></div></td>");
            }
            sb.append("</tr>");
        }


      Map map=new HashMap();
      map.put("html",sb.toString());
      return map;
    }

    @Override
    public Map<String, String> createStorageCubageHTMLB(String shelfId) {
        String code=SecurityUtils.getTenantCode().toUpperCase();
        String imageBasePath = "../../../../../img/";
        float tableWidth = 550;
        float tableHeight = 230;
        float tdLineWidth = 1;
        String trStyle = "";
        String tdStyle = "border-width:1px;cursor:pointer;";

        String tdClickEvent = "showInfo(grid,guiid,storeid,'position')";

       // shelfId = shelfId.substring(2, shelfId.length());
        //A,B面
        Grid grid=new Grid();
        grid.setGridSide("B");
        grid.setShelfId(Long.parseLong(shelfId));
        List<Grid> geList =gridMapper.selectGridList(grid,SecurityUtils.getTenantCode().toUpperCase());//result   A面的所有格子
        Shelf shelf = shelfMapper.getShelfById(Long.parseLong(shelfId),code);//result1   当前的档案柜

        int iCol = shelf.getShelfStand();
        int iRow = shelf.getShelfCross();

        //select code from sys_dict where dict_type_id=(select dict_type_id from sys_dict_type where code ='DAGPLSX' limit 1) and status='ENABLE' limit 1
        //YSDX 由上到下;YXDS 由下到上
        float imageWidth = (tableWidth - (iCol - 1) * tdLineWidth) / iCol;
        float imageHeight = (tableHeight - (iRow - 1) * tdLineWidth) / iRow;
        float imageTdWidth = 1;
        if (null != geList && geList.size() > 0) {
            imageTdWidth = imageWidth /  30;//计算格子中的盒子图片的宽度
            imageTdWidth = imageTdWidth < 1 ? 1 : imageTdWidth;
        }

        String html = new String();
        StringBuffer sb = new StringBuffer(500);

            for (int r = 0; r < iRow; r++) {
                int pai=r+1;
                if (null == geList || geList.size() == 0) {
                    break;
                }
                sb.append("<tr ").append("style='").append(trStyle).append("'>");
                for (int c = 0; c < iCol; c++) {
                    int lie=c+1;
                    int orderNo = pai+(lie-1)*iRow;
                    Grid danganGeMap = geList.get(orderNo - 1);
                    String positionString=shelf.getStoreCde()+" "+shelf.getKfqy()+" "+shelf.getShelfCode()+" "+"B面"+" "+danganGeMap.getGridCode();

                    String tdClickEventTmp = tdClickEvent.replaceAll("grid", danganGeMap.getGridId().toString());
                    tdClickEventTmp = tdClickEventTmp.replaceAll("guiid", danganGeMap.getShelfId().toString());
                    tdClickEventTmp = tdClickEventTmp.replaceAll("storeid", shelf.getStoreId().toString());
                    tdClickEventTmp = tdClickEventTmp.replaceAll("position", positionString);

                    StringBuffer title = new StringBuffer();
                    title.append("存址编号：");
                    title.append(danganGeMap.getGridName());
                    /*
                     *  title.append("\n已用空间：");
                     * title.append(danganGeMap.get("USE_WIDTH")); title.append("\n剩余空间："); float
                     * cubageNum = Integer.parseInt(danganGeMap.get("SY_WIDTH")); if (cubageNum < 0)
                     * { cubageNum = 0; } title.append(cubageNum);
                     */
                    StringBuffer sbImageTd = new StringBuffer();

                    Long grid_id = danganGeMap.getGridId();
                    int count = boxMapper.getUpShelvesNum(grid_id,code);

                    if (count <= 0) {
                        for (int j = 0; j <  30; j++) {
                            sbImageTd.append("<td class='EmptyRack' style='width:" + imageTdWidth + "px;height:"
                                    + imageHeight + "px;'></td>");
                        }
                    } else {
                        int index = 0;
                        int k = 0;
                        for (int i = 0; i <  30; i++) {
                            if (index ==30) {
                                break;
                            }
                            index++;
                            if (k < count) {
//                                sbImageTd.append("<td><img class=\"img\" src='" + imageBasePath + "cubage_use_1.jpg' width='"
//                                        + imageTdWidth + "' height='" + imageHeight + "' style=\"background-color: #d69632;\" /></td>");
                                sbImageTd.append("<td class='listClass' style='width:" + imageTdWidth + "px;height:" + imageHeight +
                                        "px;'></td>");
                                k++;

                            } else {
                                sbImageTd.append("<td class='EmptyRack' style='width:" + imageTdWidth + "px;height:"
                                        + imageHeight + "px;'></td>");
                            }
                        }
                   /*     float image0s = Float.parseFloat(danganGeMap.getGridWidth().toString()) / 30 - Float.parseFloat(boxMapper.getUpShelvesNumByFolderId(danganGeMap.getGridId(),code)+"");;
                        image0s = image0s < 0 ? 0 : image0s;
                        for (int j = 0; j < image0s; j++) {
                            if (index == Float.parseFloat(danganGeMap.getGridWidth().toString()) / 30) {
                                break;
                            }
                            index++;
                            sbImageTd.append("<td class='EmptyRack' style='width:" + imageTdWidth + "px;height:"
                                    + imageHeight + "px;'></td>");
                        }*/
                    }

                    //String tdText = danganGeMap.get("GRID_STDNUM") + "-" + danganGeMap.get("GRID_CRSNUM");
                    int tdText =pai+(lie-1)*iRow;
                    sb.append("<td id=\"" + danganGeMap.getGridId() + "\"").append("style='").append(tdStyle)
                            .append("background-image: linear-gradient( #c9caca, #737373);height:"+imageHeight+"px;")//整个格子的背景颜色
                            .append("' align='center' @click=\"" + tdClickEventTmp + "\"")
                            .append("title=\"" + title.toString() + "\">").append("<div>");
                    sb.append(
                            "<table style=\"position:relative;z-index:1;top:0px;left:0px;\" cellpadding=\"0\" cellspacing=\"0\"><tr>");
                    sb.append(sbImageTd);
                    sb.append("</tr></table>");
                    sb.append("<div style='position:relative;z-index:2;top:-15px;left:0px;height:0px;'>");
                    sb.append("<font color='#ffffff' style='font-size:10px'>" + tdText+"格");
                    sb.append("</font></div></div></td>");
                }
                sb.append("</tr>");
            }

        html = sb.toString();
        Map<String, String> ret = new HashMap();
        ret.put("html", html);
        return ret;
    }

    @Override
    public Grid getInfo(Long gridId) {
        Grid grid=gridMapper.selectGridByGridId(gridId,SecurityUtils.getTenantCode().toUpperCase());

       return grid;

    }

    @Override
    public List<Map<String, Object>> selectDaList(Map map) {
        String code=SecurityUtils.getTenantCode().toUpperCase();
        if(StringUtils.isEmpty(code)){
            throw new ServiceException("TenantCode is null");

        }
        //根据上架类型去判断
       String type=map.get("type").toString();
       Long gzId=Long.parseLong(map.get("gridId").toString());
       //0为按盒上架 1为按卷上架
       List<Map<String,Object>> list=new ArrayList<>();
        if("0".equals(type)){
            list=gridMapper.getDaList(gzId,code);
       }else if("1".equals(type)){
            list=gridMapper.getFolderList(gzId,code);
       }

        return list;
    }

    @Override
    public List getTreeList(String par_id) {
        String tenantCode = SecurityUtils.getTenantCode();
        List<Map<String, Object>> listMap = null;
        if (par_id != null) {
            if (par_id.startsWith("k_")) {
                par_id=par_id.substring(2,par_id.length());
                //获取区域
                Storeroom storeroom=storeroomMapper.selectStoreroomByStoreId(Long.parseLong(par_id),tenantCode.toUpperCase());
                Integer fenqu=storeroom.getIsFenqu();
                if(fenqu==0){
                    listMap = shelfMapper.getShelfs(Long.parseLong(par_id), tenantCode.toUpperCase(),"");
                }else{
                    if(par_id.indexOf(";")>-1){
                        listMap = shelfMapper.getShelfs(Long.parseLong(par_id.split(";")[0]), tenantCode.toUpperCase(),par_id.split(";")[1]);
                    }else{
                        String region=storeroom.getRegion();
                        if(region.indexOf(";")>-1){
                            String [] regionArr=region.split(";");
                            for(String arr:regionArr){
                                Map<String,Object> map=new HashMap<>();
                                map.put("id","k_"+par_id+";"+arr);
                                map.put("text",arr);
                                int count= shelfMapper.getCountByRegion(par_id,arr,tenantCode.toUpperCase());
                                if(count>0){
                                    map.put("children","true");
                                }else{
                                    map.put("children","false");
                                }
                                listMap.add(map);
                            }
                        }else{
                            Map<String,Object> map=new HashMap<>();
                            map.put("id","k_"+par_id+";"+region);
                            map.put("text",region);
                            int count= shelfMapper.getCountByRegion(par_id,region,tenantCode.toUpperCase());
                            if(count>0){
                                map.put("children","true");
                            }else{
                                map.put("children","false");
                            }
                            listMap.add(map);
                        }

                    }

                }

            } else if (par_id.startsWith("g_")) {
                par_id=par_id.substring(2,par_id.length());
                listMap = gridMapper.getGrids(Long.parseLong(par_id),tenantCode.toUpperCase());
            } else {
                par_id=par_id.substring(2,par_id.length());
                listMap = storeroomMapper.getStores(tenantCode.toUpperCase());
            }
        } else {
            listMap = storeroomMapper.getStores(tenantCode.toUpperCase());
        }
        String treenodes = "";
        List<Map<String, Object>> rootMap = new ArrayList<Map<String, Object>>();
        if (listMap != null && listMap.size() > 0) {
            // 转换节点数据
            for (Map tmp : listMap) {
                tmp.put("id", tmp.get("id"));
                tmp.put("text", tmp.get("text"));
                if (String.valueOf(tmp.get("children")).equals("true")) {
                    tmp.put("children", true);
                } else {
                    tmp.put("children", false);
                }
                if(String.valueOf(tmp.get("id")).startsWith("k_")) {
                    tmp.put("type", "kufang");
                }else if(String.valueOf(tmp.get("id")).startsWith("g_")) {
                    tmp.put("type", "shelf");
                }else {
                    tmp.put("type", "grid");
                }
                Map<String, Object> m = new HashMap<String, Object>();
                m.put("title", tmp.get("text"));
                tmp.put("a_attr", m);
            }
            // 只在第一次加载第一级
            if ("-1".equals(par_id)) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("text", "库房树");
                map.put("id", "-1");
                Map<String, Object> m = new HashMap<String, Object>();
                m.put("opened", true);
                m.put("selected", false);
                map.put("state", m);
                map.put("type", "root");
                map.put("children", listMap);
                rootMap.add(map);
            } else {
                rootMap = listMap;
            }
        } else {
            if ("-1".equals(par_id)) {
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("text", "库房树");
                map.put("id", "-2");
                Map<String, Object> m = new HashMap<String, Object>();
                m.put("opened", true);
                m.put("selected", false);
                map.put("state", m);
                map.put("type", "root");
                rootMap.add(map);
            }
        }
        return rootMap;
    }
}
